package com.sgb.kjwl.view.ui.activity.self.publish;

import static com.swgk.core.event.EventConstant.EVENT_BRAND_ADD;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityGoodsAlbumBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.AlbumEntity;
import com.swgk.core.event.EventConstant;
import com.sgb.link.event.MaterialEvent;
import com.sgb.kjwl.view.event.self.GoodsEvent;
import com.sgb.kjwl.view.ui.adapter.material.SelectNetImgAdapter;
import com.sgb.kjwl.viewmodel.self.publish.GoodsAlbumModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.BaseRecycleAdapter;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class GoodsAlbumActivity extends AppActivity {
    private ActivityGoodsAlbumBinding binding;
    private String id;
    private String name;
    private GoodsEvent goodsEvent;
    private List<AlbumEntity> datas;
    private List<AlbumEntity> albumListName;
    private SelectNetImgAdapter adapter;
    private List<String> selectUrl;
    private int albumPosition;
    private int size;
    @Inject
    GoodsAlbumModel viewModel;

    public static void start(Context context, String id, String name, Object object, int position) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString("id", id);
        bundle.putString("name", name);
        bundle.putInt("position", position);
        bundle.putSerializable("datas", (Serializable) object);
        intent.putExtras(bundle);
        intent.setClass(context, GoodsAlbumActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    public static void start(Context context, Intent extras) {
        Intent intent = new Intent();
        intent.setClass(context, GoodsAlbumActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (extras != null) {
            intent.putExtras(extras);
        }
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder()
                .appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initView() {
        id = getIntent().getStringExtra("id");
        name = getIntent().getStringExtra("name");
        albumPosition = getIntent().getIntExtra("position", 0);
        albumListName = (List<AlbumEntity>) getIntent().getSerializableExtra("datas");
        binding = DataBindingUtil.setContentView(GoodsAlbumActivity.this, R.layout.activity_goods_album);
        binding.setViewModel(viewModel);
        binding.tvTitle.setText(name);
        binding.tvCancel.setOnClickListener(this);
        binding.backView.setOnClickListener(this);
        binding.tvCompany.setOnClickListener(this);
        binding.replaceAlbum.setOnClickListener(this);

        binding.rvAlbum.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        if (adapter == null)
            adapter = new SelectNetImgAdapter(getActivity(), null);
        adapter.setMultiSelect(true);
        adapter.setOnItemMultiClick(new BaseRecycleAdapter.OnItemMultiClick<AlbumEntity>() {
            @Override
            public void onItemMultiClick(List<AlbumEntity> albumEntities, int position) {
                if (albumEntities.size() != 0) {
                    binding.tvCancel.setVisibility(View.VISIBLE);
                    binding.backView.setVisibility(View.GONE);
                } else {
                    binding.tvCancel.setVisibility(View.GONE);
                    binding.backView.setVisibility(View.VISIBLE);
                }
                binding.tvCompany.setText("完成(" + albumEntities.size() + ")");
            }
        });
        binding.rvAlbum.setAdapter(adapter);
        binding.rvAlbum.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                viewModel.getSupplierPhotosByAlbumId(false, id);
            }

            @Override
            public void onLoadMore() {
            }
        });
        binding.rvAlbum.setLoadingMoreEnabled(false);
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void init() {
        viewModel.getSupplierPhotosByAlbumId(false, id);
    }


    public void showSuccess() {
        goodsEvent = new GoodsEvent();
        goodsEvent.setMessageTag(EVENT_BRAND_ADD);
        EventBus.getDefault().post(goodsEvent);
        finish();
    }

    public void showList(List<AlbumEntity> data, boolean isLodMore) {
        this.datas = data;
        adapter.setDatas(data);
        binding.rvAlbum.refreshComplete();
        if (selectUrl != null && selectUrl.size() != 0) {
            //取消默认的选中，保持和IOS一致
            for (int i = 0; i < selectUrl.size(); i++) {
                for (int j = 0; j < data.size(); j++) {
                    if (selectUrl.get(i).equals(data.get(j).getImageUrl())) {
                        adapter.setCheckDefault(j);
                        size++;
                    }
                }
            }
            adapter.setMost(size);
            binding.tvCancel.setVisibility(View.VISIBLE);
            binding.backView.setVisibility(View.GONE);
        } else {
            adapter.setMost(8);
            binding.tvCancel.setVisibility(View.GONE);
            binding.backView.setVisibility(View.VISIBLE);
        }
        binding.tvCompany.setText("完成(" + adapter.getCheckDatas().size() + ")");
    }

    public void showAlbumPop() {
        //条件选择器
        OptionsPickerView optionsPickerView = new OptionsPickerBuilder(GoodsAlbumActivity.this, (options1, options2, options3, v) -> {
            String content = albumListName.get(options1).getName();
            binding.tvTitle.setText(content);
            albumPosition = options1;
            id = albumListName.get(albumPosition).getId();
            adapter.resetCheckDatas();
            binding.tvCancel.setVisibility(View.GONE);
            binding.backView.setVisibility(View.VISIBLE);
            viewModel.getSupplierPhotosByAlbumId(false, id);
        }).build();
        optionsPickerView.setPicker(albumListName);
        optionsPickerView.setSelectOptions(albumPosition);
        optionsPickerView.setTitleText("图库选择");
        optionsPickerView.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_company:
                List<AlbumEntity> select = adapter.getCheckDatas();
                if (selectUrl == null)
                    selectUrl = new ArrayList<>();
                selectUrl.clear();
                for (int i = 0; i < select.size(); i++) {
                    selectUrl.add(select.get(i).getImageUrl());
                }
                List<AlbumEntity> allData = adapter.getDatas();
                allData.removeAll(select);
                List<String>  unSelectUrl =new ArrayList<>();
                for (int a = 0; a < allData.size(); a++) {
                    unSelectUrl.add(allData.get(a).getImageUrl());
                }
                EventBus.getDefault().post(MaterialEvent.make().setMessageTag(EventConstant.EVENT_GOODS_NET_IMG_SELECT).setObject(selectUrl).setMessageData(unSelectUrl));
                finish();
                break;
            case R.id.tv_cancel:
                adapter.resetCheckDatas();
                binding.tvCompany.setText("完成(0)");
                binding.tvCancel.setVisibility(View.GONE);
                binding.backView.setVisibility(View.VISIBLE);
                break;
            case R.id.back_view:
                finish();
                break;
            case R.id.replace_album:
                showAlbumPop();
                break;
            default:
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(MaterialEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_GOODS_NET_IMG_SELECT_RE) {
            size = (int) event.getObject();
            selectUrl = new ArrayList<>();
            selectUrl = (List<String>) event.getMessageData();
        }
        EventBus.getDefault().removeStickyEvent(event);
    }
}

